﻿namespace YunQue.Core.WebExtension.Filters
{
    /// <summary>
    /// 请求过滤器
    /// </summary>
    public class RequestAsyncFilter : IAsyncActionFilter
    {
        private readonly LogHelper _logger;
        /// <summary>
        /// 异步请求过滤器
        /// </summary>
        /// <param name="logger"></param>
        public RequestAsyncFilter(LogHelper logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 记录请求日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 执行方法前记录请求日志
            context.HttpContext.Request.Headers[AppSettingManager.TRANCEID] = Guid.NewGuid().ToString();
            LogRequest(context);
            //记录请求时长
            Stopwatch sw = new Stopwatch();
            sw.Start();
            // 执行方法
            var resultContext = await next();
            sw.Stop();
            // 执行方法后记录响应日志
            LogResponse(context, sw.ElapsedMilliseconds);
        }
        /// <summary>
        /// 执行前记录请求日志
        /// </summary>
        /// <param name="context"></param>
        private void LogRequest(ActionExecutingContext context)
        {
            var objs = new KeyValuePair<string, object>[3];
            objs[0] = new KeyValuePair<string, object>(AppSettingManager.URL, context.HttpContext.Request.Path);
            objs[1] = new KeyValuePair<string, object>(AppSettingManager.METHOD, context.HttpContext.Request.Method);
            objs[2] = new KeyValuePair<string, object>(AppSettingManager.PARAMETER, JsonConvert.SerializeObject(context.ActionArguments));
            _logger.LogInformation($"{context.HttpContext.Request.Path} Start", objs);
        }
        /// <summary>
        /// 执行后记录响应日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="usingTime"></param>
        private void LogResponse(ActionExecutingContext context, long usingTime)
        {
            var objs = new KeyValuePair<string, object>[5];
            objs[0] = new KeyValuePair<string, object>(AppSettingManager.URL, context.HttpContext.Request.Path);
            objs[1] = new KeyValuePair<string, object>(AppSettingManager.METHOD, context.HttpContext.Request.Method);
            objs[2] = new KeyValuePair<string, object>(AppSettingManager.PARAMETER, JsonConvert.SerializeObject(context.ActionArguments));
            objs[3] = new KeyValuePair<string, object>(AppSettingManager.USINGTIME, usingTime);
            objs[4] = new KeyValuePair<string, object>("ResultData", JsonConvert.SerializeObject(context.HttpContext.Response.StatusCode));
            _logger.LogInformation($"{context.HttpContext.Request.Path} End", objs);
        }
    }
}
